package com.ghsc.ghxc.jsb.ui.integral.fragment

import android.graphics.Paint
import android.os.Bundle
import android.text.TextUtils
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.cn.appcore.base.BaseVMFragment
import com.cn.appcore.event.RxBus
import com.cn.appcore.event.RxBusBean
import com.cn.appcore.event.SchedulerTransformer
import com.cn.appcore.ext.getCompatColor
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.setOnFastChildClickListener
import com.cn.appcore.ext.showToast
import com.cn.appcore.ext.startKtxActivity
import com.cn.appcore.utils.GlideUtil
import com.cn.appcore.utils.GsonUtil
import com.cn.appcore.widget.CustomRefreshListener
import com.cn.appcore.widget.RefreshHelper
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.databinding.RefreshListBinding
import com.ghsc.ghxc.jsb.ui.integral.IntegralSupermarketViewModel
import com.ghsc.ghxc.jsb.ui.integral.activity.ReleaseCommodityActivity
import com.ghsc.ghxc.jsb.ui.integral.activity.TabActivity
import com.ghsc.ghxc.jsb.ui.integral.bean.ReleaseBean
import com.ghsc.ghxc.jsb.ui.my.activity.OrderDetailActivity
import com.ghsc.ghxc.jsb.ui.my.bean.OrderBean
import com.ghsc.ghxc.jsb.view.ConfirmCancelPopViiew
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.scwang.smart.refresh.layout.api.RefreshLayout

/**
 * 项目：GuoHuaJsb
 * 包名：com.ghsc.ghxc.jsb.ui.integral.fragment
 * 类名：MyReleaseListFragment
 * 创建时间：2024/5/20 14:15
 * 创建人 @author： xiaolin
 * 描述 ：Todo...我发布的
 */
class MyReleaseListFragment  : BaseVMFragment<IntegralSupermarketViewModel, RefreshListBinding>(R.layout.refresh_list) {
    override fun attachVMClass(): Class<IntegralSupermarketViewModel>? {
        return  IntegralSupermarketViewModel::class.java
    }
    var index: Int = 0

    companion object {
        fun getInstance(index: Int): MyReleaseListFragment? {
            var fragment = MyReleaseListFragment()
            fragment.index = index
            return fragment
        }
    }
    override fun lazyLoad() {

    }
    var isInit=false
    private val mAdapter by lazy { ListAdapter() }
    var mList = arrayListOf<ReleaseBean>()
    override fun initView(savedInstanceState: Bundle?) {
        binding.rvList.layoutManager = LinearLayoutManager(requireActivity())
        binding.rvList.adapter = mAdapter
        mAdapter.replaceData(mList)
        mAdapter.setEmptyView(R.layout.layout_order_empty)
        mAdapter.addChildClickViewIds(R.id.tvBtnDelete,R.id.tvBtnSub)
        initRefreshLayout()
        rxBusSubscription = RxBus.getDefault().toObservable(RxBusBean::class.java)
            .compose(SchedulerTransformer())
            .subscribe{ rxBusBean ->
                 if (rxBusBean.id == CustKey.ORDER_TAB && rxBusBean.sign == CustKey.ORDER_TAB) {
                    var tabIndex =rxBusBean.anyBean as Int
                    if(tabIndex==index){
                        if (isInit){
                            binding.refreshLayout.autoRefresh()
                        }
                    }
                }
            }
    }

    private fun initRefreshLayout() {
        RefreshHelper.initRefreshLayout(binding.refreshLayout, object : CustomRefreshListener {
            override fun _onRefresh(refreshLayout: RefreshLayout?) {
                pageNo = 1
                getListData()
            }

            override fun _onLoadMore(refreshLayout: RefreshLayout?) {
                pageNo++
                getListData()
            }
        })
    }


    override fun onResume() {
        super.onResume()
        loge("刷新onResume")
        pageNo = 1
        getListData()
    }


    private fun getListData() {
        //审核状态 0，未通过审核，1：通过审核
        val map: HashMap<String, Any> = HashMap()
        map["pindex"] = pageNo
        map["psize"] = pageSize
        map["status"] = index
        loge("请求接口="+index+"当前页"+pageNo)
        GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onMyGoodListMethod(it1) }
    }


    override fun initClickListener() {
        super.initClickListener()
        mAdapter.setOnItemClickListener { adapter, view, position ->
            //跳转修改页面。
            startKtxActivity<ReleaseCommodityActivity>(
                value =  "pid" to mAdapter.data[position].pid
            )
        }
        mAdapter.setOnFastChildClickListener { view, position ->
            val bean = mAdapter.data[position]
            when (view.id) {
                R.id.tvBtnDelete -> {
                    XPopup.Builder(requireActivity())
                        .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                        .customHostLifecycle(lifecycle)
                        .navigationBarColor(getCompatColor(R.color.bg_dark_color))
                        .asCustom(
                            ConfirmCancelPopViiew(
                                requireActivity(), "提示", "确定要删除该商品吗?",
                                btnConfirm = {
                                    val map: HashMap<String, Any> = HashMap()
                                    map["pid"] = bean.pid
                                    GsonUtil.mapToJsonStrObjEncryption(map)
                                        ?.let { it1 -> mViewModel.onDelGoodsMethod(it1) }
                                },
                                btnCancel = {
                                },
                            )
                        )
                        .show()
                }

                R.id.tvBtnSub -> {
                    //下架
                    XPopup.Builder(requireActivity())
                        .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                        .customHostLifecycle(lifecycle)
                        .navigationBarColor(getCompatColor(R.color.bg_dark_color))
                        .asCustom(
                            ConfirmCancelPopViiew(
                                requireActivity(), "提示", "确定要下架该商品吗?",
                                btnConfirm = {
                                    val map: HashMap<String, Any> = HashMap()
                                    map["pid"] = bean.pid
                                    GsonUtil.mapToJsonStrObjEncryption(map)
                                        ?.let { it1 -> mViewModel.onUpdIfonSaleMethod(it1) }
                                },
                                btnCancel = {
                                },
                            )
                        )
                        .show()
                }
            }
        }
    }


    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@MyReleaseListFragment) {
                RefreshHelper.finishRefresh(binding.refreshLayout, pageNo)
                showToast(it)
            }
            againLoginMsg.observe(this@MyReleaseListFragment) {
                RefreshHelper.finishRefresh(binding.refreshLayout, pageNo)
                showToast(CustKey.IN_AGAIN_MSG)
                LoginHelper.startLoginPage()
            }
            onMyGoodListData.observe(this@MyReleaseListFragment) {
                RefreshHelper.finishRefresh(binding.refreshLayout, pageNo)
                if (pageNo == 1) {
                    if (it.data.list.isNullOrEmpty()){
                        mAdapter.replaceData(it.data.list)
                        mAdapter.setEmptyView(R.layout.layout_order_empty)
                    }
                    else {
                        mAdapter.replaceData(it.data.list)
                    }
                } else {
                    if (!it.data.list.isNullOrEmpty())
                        mAdapter.addData(it.data.list)
                }
                isInit=true
            }

            onDelGoodsData.observe(this@MyReleaseListFragment){
                //删除
                showToast("操作成功")
                binding.refreshLayout.autoRefresh()
            }
            onUpdIfonSaleData.observe(this@MyReleaseListFragment){
                //上架 下架
                showToast("操作成功")
                binding.refreshLayout.autoRefresh()
            }

        }
    }
    inner class ListAdapter : BaseQuickAdapter<ReleaseBean, BaseViewHolder>(R.layout.release_list_item) {
        override fun convert(holder: BaseViewHolder, item: ReleaseBean) {
            GlideUtil.ImageLoad(this.context,item.images,holder.getView(R.id.images))
            holder.setText(R.id.title,item.title)
                .setText(R.id.memo,item.memo)
                .setText(R.id.tvPrice,if (TextUtils.isEmpty(item.price))"0.0" else item.price)
                .setText(R.id.tvOriprice,if (TextUtils.isEmpty(item.oriprice))"0.0 积分" else item.oriprice+" 积分")
                .setText(R.id.tvBtnSub,if(item.ifonsale==0) "上架" else "下架")
//            if(!TextUtils.isEmpty(item.oriprice))
                holder.getView<TextView>(R.id.tvOriprice).paint.flags = Paint.STRIKE_THRU_TEXT_FLAG


            if(index==1){
                //审核通过
                holder.setGone(R.id.tvBtnDelete,true)
                    .setGone(R.id.tvBtnSub,false)
            }
            if(index==0){
               //待审核
                holder.setGone(R.id.tvBtnDelete,false)
                    .setGone(R.id.tvBtnSub,false)
            }
            if(index==3){
                //审核未通过
                holder.setGone(R.id.tvBtnDelete,false)
                    .setGone(R.id.tvBtnSub,true)
            }
        }
    }
}